package thread.interrupt;



/*
Aim:
验证1: 无阻塞线程，即使中断状态被置为true,线程可以采集到自己的中断状态，但是否继续运行由程序逻辑自己决定
验证2: 首先 设定中断状态为true,然后再使线程阻塞，这时，线程将会抛出InterruptedException，并且清除中断状态，即重置中断状态为false.
*/
public class NoBlockInterruptDemo implements Runnable{

        static boolean  stop = false;   
        public static void main(String[] args) throws Exception {   
            Thread thread = new Thread(new NoBlockInterruptDemo(),"My Thread");
            System.out.println( "Starting thread..." );   
            thread.start();   
            Thread.sleep( 3000 );   
            System.out.println( "Interrupting my thread..." );
            thread.interrupt();   
            System.out.println("线程中断状态是否为true：" + thread.isInterrupted());
            Thread.sleep( 3000 );
            System.out.println("拟改变My thread 的状态：无阻塞->阻塞");
            stop=true;
            System.out.println("Stopping main thread..." );
        }   
        public void run() {   
            while(!stop){   
                System.out.println( "My Thread is running without no block..." );   
                // 让该循环持续一段时间，使上面的话打印次数少点   
                long time = System.currentTimeMillis();   
                while((System.currentTimeMillis()-time < 1000)) {   
                }   
            }
            try {
                while (true){
                    Thread.currentThread().sleep(1000);
                }
            } catch (InterruptedException e) {
                System.out.println("阻塞状态，被InterruptedException打破，进入异常处理 ");
                System.out.println("检查阻塞状态被InterruptedException打破后的，中断状态为： "+Thread.currentThread().isInterrupted());
                //e.printStackTrace();
            }
            System.out.println("My thread 即将从 catch块中运行结束....");

        }   
    }   